package com.itheima.w_util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import org.yaml.snakeyaml.Yaml;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

public class YamlToJavaClassGenerator {
    
    /**
     * 将 YAML 文件转换为 Java 类（带 @Value 注解）
     * @param yamlFilePath YAML 文件路径
     * @param className    生成的类名
     * @param packageName  包名
     */
    public static void generateClassWithValueAnnotation(
            String yamlFilePath,
            String classPath,
            String className,
            String packageName,
            boolean lombokFlag) throws IOException {
        
        Yaml yaml = new Yaml();
        Map<String, Object> data = yaml.load(new FileInputStream(yamlFilePath));
        
        StringBuilder sb = new StringBuilder();
        sb.append("package ").append(packageName).append(";\n\n");
        sb.append("import org.springframework.beans.factory.annotation.Value;\n");
        if (lombokFlag){
            sb.append("import lombok.Getter;\n");
        }
        sb.append("import org.springframework.stereotype.Component;\n\n");
        sb.append("@Component\n");
        if (lombokFlag){
            sb.append("@Getter\n");
        }
        sb.append("public class ").append(className).append(" {\n\n");
        
        generateFields(sb, data, "");
        
        sb.append("}\n");
        String filePath = StrUtil.join(File.separator, classPath, className + ".java");
        FileUtil.mkParentDirs(filePath);
        FileUtil.writeString(sb.toString(),filePath, CharsetUtil.CHARSET_UTF_8);
    }

    public static void generateConfClass(String yamlFilePath,
                                         String classPath,
                                         String packageName)  {
        try {
            generateClassWithValueAnnotation(
                    yamlFilePath,
                    classPath,
                    "SystemConfig",
                    packageName,true);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static void generateFields(
            StringBuilder sb, 
            Map<String, Object> data, 
            String parentPath) {
        
        data.forEach((key, value) -> {
            String fullPath = parentPath.isEmpty() ? key : parentPath + "." + key;
            
            if (value instanceof Map) {
                // 处理嵌套对象
                generateFields(sb, (Map<String, Object>) value, fullPath);
            } else {
                // 生成字段和注解
                String typeName = getJavaType(value);
                sb.append("\t@Value(\"${").append(fullPath).append("}\")\n");
                sb.append("\tprivate ").append(typeName).append(" ")
                  .append(StrUtil.lowerFirst(toCamelCase(key))).append(";\n\n");
            }
        });
    }

    private static String getJavaType(Object value) {
        if (value instanceof Integer) return "Integer";
        if (value instanceof Long) return "Long";
        if (value instanceof Double) return "Double";
        if (value instanceof Boolean) return "Boolean";
        if (value instanceof List) return "List<?>"; // 简化为通用 List
        return "String"; // 默认类型
    }

    private static String toCamelCase(String str) {
        return Arrays.stream(str.split("[-_]"))
            .map(s -> s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase())
            .reduce("", String::concat);
    }


}
